//
//  CommunityViewModel.swift
//  NDAi
//
//  Created by 丸子 on 2024/8/19.
//

import UIKit

class CommunityViewModel {
    var isFirst:Bool = false
    var dataArr:[CommunityModel] = []
    var page = 1
    let reloadDataSubject = PublishSubject<Void>()
    let createSuccessSubject = PublishSubject<String>()
    let likeSubject = PublishSubject<Int>()

    func getDataList(){
        NDProgressHUD.showLoading()
        RequestService.instance.communityList(page: page) { model in
            NDProgressHUD.hide()
            if self.page == 1 {
                self.dataArr = model
            }else {
                self.dataArr += model
            }
            self.reloadDataSubject.onNext(())
        } failureClosure: { error in
            NDProgressHUD.showError(title: error ?? "", subtitle: error ?? "")
        }
    }
   
    
    func clickLike(model:CommunityModel) {
        let type = model.is_like == 0 ? 1 : 0
        NDProgressHUD.showLoading()
        RequestService.instance.communityLike(community_id: "\(model.id ?? 0)", type: type) { [weak self] in
            NDProgressHUD.hide()
            if type == 0 {
                NDProgressHUD.showSuccess(title: "", subtitle: "取消成功")
            }else {
                NDProgressHUD.showSuccess(title: "", subtitle: "点赞成功")
            }
            if let index = self?.dataArr.firstIndex(where: { $0.id == model.id ?? 0}) {
                self?.dataArr[index].is_like = type
            }else {
                GlobalRx.updateHomeData.onNext(model.id ?? 0)//更新封面信息
            }
            self?.likeSubject.onNext(type)
        } failureClosure: { error in
            NDProgressHUD.showError(title: error ?? "", subtitle: error ?? "")
        }
    } 
}
